package com.yiwyn.demo.base;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yiwyn.demo.domain.SUser;
import com.yiwyn.demo.mapper.SUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheUtils {

    public Cache<String, Cache<Class<?>, Object>> cache;


    public CacheUtils() {
        cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).build();
    }

    @Autowired
    private SUserMapper sUserMapper;


    //获取cache
    public <T> T get(String key, Class<? extends T> clazz) {
        Cache<Class<?>, Object> keyCache = cache.get(key, s -> Caffeine.newBuilder().build());

        Object o = keyCache.get(clazz, aClass -> {
            log.info("key:{}", key);
            Object result = null;
            if (aClass.equals(SUser.class)) {
                result = sUserMapper.selectByPrimaryKey(Long.valueOf(key));
            }
            return result;
        });
        return clazz.cast(o);
    }

}
